package com.durian.finance.controller;

import cn.hutool.core.bean.BeanUtil;
import com.durian.common.async.AsyncPushService;
import com.durian.common.core.web.controller.BaseController;
import com.durian.common.core.web.domain.AjaxResult;
import com.durian.common.log.annotation.Log;
import com.durian.common.log.enums.BusinessType;
import com.durian.common.security.annotation.Logical;
import com.durian.common.security.annotation.RequiresPermissions;
import com.durian.finance.service.IJrProductService;
import com.durian.financial.api.domain.JrProduct;
import com.durian.financial.api.domain.enums.*;
import com.durian.financial.api.domain.vo.JrProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 金融产品Controller
 * 
 * @author durian
 * @date 2022-06-22
 */
@RestController
@RequestMapping("/product")
public class JrProductController extends BaseController
{
    @Autowired
    private IJrProductService jrProductService;

    @Resource
    private AsyncPushService asyncPushService;

    private final String PASSED_ID = "NJziE3dbwfHd9ilvMkLaavSpMgsQiUxgtzPnfioVayM";
    private final String NOT_PASSED_ID = "Img4HOBVmDm5HPRFOtoaueqSgr-cyuj86KO-97rJ7Ww";

    /**
     * 查询金融产品列表 --> 租房分期，收房贷，应收租约保理列表
     * 1: 租房分期，2：收房贷 ，3：应收租约保理
     */
    @RequiresPermissions("finance:product:list")
    @GetMapping("/productMap")
    public AjaxResult productMap(JrProductVO vo)
    {

        Map<Integer,List<JrProduct>> productMap = jrProductService.selectJrProductList(vo);
        return AjaxResult.success("成功", productMap);
    }

//    /**
//     * 导出金融产品列表
//     */
//    @RequiresPermissions("finance:product:export")
//    @Log(title = "金融产品", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, JrProduct jrProduct)
//    {
//        List<JrProduct> list = jrProductService.selectJrProductList(jrProduct);
//        ExcelUtil<JrProduct> util = new ExcelUtil<JrProduct>(JrProduct.class);
//        util.exportExcel(response, list, "金融产品数据");
//    }

    /**
     * 获取金融产品详细信息
     */
    @RequiresPermissions("finance:product:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(jrProductService.selectJrProductById(id));
    }

    /**
     * 新增金融产品
     */
    @RequiresPermissions("finance:product:add")
    @Log(title = "金融产品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated JrProduct jrProduct)
    {
        return toAjax(jrProductService.insertJrProduct(jrProduct));
    }

    /**
     * 修改金融产品
     */
    @RequiresPermissions("finance:product:edit")
    @Log(title = "金融产品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JrProduct jrProduct)
    {

        JrProduct verify = jrProductService.selectJrProductById(jrProduct.getId());
        if (Objects.isNull(verify)){

            return AjaxResult.error("修改产品不存在！");
        }

        // 如果是通过状态，不可以修改
        if (Objects.equals(verify.getApplyState(),ProductApplyEnum.PASSED)){

            return AjaxResult.error("该产品已被通过！不可修改！");
        }

        // 如果已被删除
        if (Objects.equals(verify.getDelFlg(),1)){

            return AjaxResult.error("产品已被删除，不可修改！");
        }

        // 如果是从驳回修改为通过
        if (Objects.equals(verify.getApplyState(),ProductApplyEnum.NOT_PASSED)
                && Objects.equals(jrProduct.getApplyState(),ProductApplyEnum.PASSED)){

            return AjaxResult.error("当前产品已被驳回！");
        }

        // 如果是从待审核修改状态
        if (Objects.equals(verify.getApplyState(),ProductApplyEnum.CHECK_PENDING)){

            // 拷贝属性值
            BeanUtil.copyProperties(verify.setApplyState(jrProduct.getApplyState()),jrProduct);

        } else if (Objects.equals(verify.getApplyState(),ProductApplyEnum.NOT_PASSED)){

            // 如果是驳回的商品修改信息，将状态重新更新为待审核
            jrProduct.setApplyState(ProductApplyEnum.CHECK_PENDING);
        }

        // 修改
        int upCount = jrProductService.updateJrProduct(jrProduct);

        if (upCount > 0){

            // 已通过
            if (Objects.equals(jrProduct.getApplyState(),ProductApplyEnum.PASSED)){

                asyncPushService.asyncPush(PASSED_ID);
            } else if (Objects.equals(jrProduct.getApplyState(),ProductApplyEnum.NOT_PASSED)){

                asyncPushService.asyncPush(NOT_PASSED_ID);
            }
        }

        return toAjax(upCount);
    }



    /**
     * 删除金融产品
     */
    @RequiresPermissions("finance:product:remove")
    @Log(title = "金融产品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(jrProductService.deleteJrProductById(id));
    }


    /**
     * 获取获取账户类型Map
     */
    @RequiresPermissions(value = {"finance:product:add","finance:product:edit"},logical = Logical.OR)
    @GetMapping("/accountTypeMap")
    public AjaxResult getAccountTypeMap(){

        Map<Integer, String> map = AccountTypeEnum.getAccountTypeMap();
        map.remove(0);
        return AjaxResult.success(map);
    }

    /**
     * 获取资金提供方Map
     */
    @RequiresPermissions(value = {"finance:product:add","finance:product:edit"},logical = Logical.OR)
    @GetMapping("/companyEnumMap")
    public AjaxResult getCompanyEnumMap(){

        Map<Long, String> map = CompanyEnum.getCompanyEnumMap();
        map.remove(-1L);
        return AjaxResult.success(map);
    }


    /**
     * 获取金融产品对应的分期期限枚举Mao
     */
    @RequiresPermissions(value = {"finance:product:add","finance:product:edit"},logical = Logical.OR)
    @GetMapping("/instalmentEnumMap/{applyType}")
    public AjaxResult getInstalmentEnumMap(@PathVariable Integer applyType){

        Map<Integer, String> oldMap = InstalmentEnum.getInstalmentEnumMap();
        Map<Integer, String> newMap = new HashMap<>();

        if (Objects.equals(applyType,1)){// 租房分期

            newMap.put(11,oldMap.get(11));
            newMap.put(23,oldMap.get(23));
        } else if (Objects.equals(applyType,2)){// 收房贷

            newMap.put(12,oldMap.get(12));
            newMap.put(24,oldMap.get(24));
        } else if (Objects.equals(applyType,3)){

            newMap.put(12,oldMap.get(12));
            newMap.put(24,oldMap.get(24));
            newMap.put(-1,oldMap.get(-1));
        }
        return AjaxResult.success(newMap);
    }


    /**
     * 获取金融产品对应的还款方式枚举Mao
     */
    @RequiresPermissions(value = {"finance:product:add","finance:product:edit"},logical = Logical.OR)
    @GetMapping("/repaymentEnumMap/{applyType}")
    public AjaxResult getRepaymentEnumMap(@PathVariable Integer applyType){

        Map<Integer, String> map = new HashMap<>();
        if (Objects.equals(applyType,1)){

            RepaymentEnum monthly = RepaymentEnum.MONTHLY;
            map.put(monthly.getIndex(),monthly.getValue());
        } else if (Objects.equals(applyType,2)){

            RepaymentEnum monthly = RepaymentEnum.MONTHLY;
            RepaymentEnum season = RepaymentEnum.SEASON;
            map.put(monthly.getIndex(), monthly.getValue());
            map.put(season.getIndex(), season.getValue());

        } else if (Objects.equals(applyType,3)){

            RepaymentEnum period = RepaymentEnum.PERIOD;
            map.put(period.getIndex(),period.getValue());
        }
        return AjaxResult.success(map);
    }
}
